package me.exchange.com.config;

import me.exchange.com.modules.system.domain.Dept;
import me.exchange.com.modules.system.dto.RoleSmallDto;
import me.exchange.com.modules.system.dto.UserDto;
import me.exchange.com.modules.system.service.DeptService;
import me.exchange.com.modules.system.service.RoleService;
import me.exchange.com.modules.system.service.UserService;
import me.exchange.com.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 数据权限配置
 * @author Zheng Jie
 * @date 2019-4-1
 */
@Component
public class DataScope {

    private final String[] scopeType = {"全部","本级","自定义"};

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DeptService deptService;

    public Long getDeptIds() {

        UserDto user = userService.findByName(SecurityUtils.getUsername());

        // 用于存储部门id
        Set<Long> deptIds = new HashSet<>();
        Long deptId =null;

        // 查询用户角色
        List<RoleSmallDto> roleSet = roleService.findByUsersId(user.getId());

        for (RoleSmallDto role : roleSet) {

            if (scopeType[0].equals(role.getDataScope())) {
                return null;
            }

            // 存储本级的数据权限
            if (scopeType[1].equals(role.getDataScope())) {
                deptId =user.getDeptId();
            }
        }
        return deptId;
    }


    public List<Long> getDeptChildren(List<Dept> deptList) {
        List<Long> list = new ArrayList<>();
        deptList.forEach(dept -> {
                    if (dept!=null && dept.getEnabled()){
                        list.add(dept.getId());
                    }
                }
        );
        return list;
    }
}
